﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoFix.Base;
using AutoFix.controls;
using Common;
using BusinessLogicLayer.Manager;
using Objects;
using System.Text;

namespace AutoFix
{
    public partial class article_list : BasePage
    {
        #region [BasePage Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage { get { return false; } }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage { get { return false; } }

        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Article List"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor}); }
        }
      
        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(Page.IsPostBack))
            {
                LoadPage();
            }
        }        
        /// <summary>
        /// Handles the item command event of the Datalist control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void dtlArticles_ItemCommand(object source, DataListCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Delete":
                    ArticleManager articleManager = new ArticleManager();
                    Article deleteArticle = new Article();
                    List<Article> articles = null;
                    try
                    {
                        articles = articleManager.GetArticles(Convert.ToInt32(e.CommandArgument));
                        if (articles != null && articles.Count > 0)
                        {
                            deleteArticle.ArticleID = articles[0].ArticleID;
                            deleteArticle.ArticleName = articles[0].ArticleName;
                            deleteArticle.ArticleImageUrl = articles[0].ArticleImageUrl;
                            deleteArticle.ArticleTypeID = articles[0].ArticleTypeID;
                            deleteArticle.VehicleModelID = articles[0].VehicleModelID;
                            deleteArticle.UserID = articles[0].UserID;
                            deleteArticle.VehicleModelTypeID = articles[0].VehicleModelTypeID;
                            deleteArticle.VehicleModelTypeYearID = articles[0].VehicleModelTypeYearID;
                            deleteArticle.IsPublished = articles[0].IsPublished;
                            deleteArticle.LastUpdatedDate = articles[0].LastUpdatedDate;
                            deleteArticle.IsActive = false;

                            bool success = articleManager.UpdateArticle(deleteArticle);
                            if (success)
                            {
                                this.pageActionMessage.InnerText = "The article deleted successfully";
                                this.pageActionMessage.Attributes.Add("class", "success-msg");
                                LoadPage();
                            }
                            else
                            {
                                this.pageActionMessage.InnerText = "Failed to delete the article.";
                                this.pageActionMessage.Attributes.Add("class", "error-msg");

                            }

                        }

                    }
                    catch (Exception)
                    {
                        this.pageActionMessage.InnerText = "Failed to delete the article.";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                    finally 
                    {
                        articleManager = null;
                        articles = null;
                        deleteArticle = null;
                    }
                    break;
                case "Edit":
                    ArticleManager editArticleManager = new ArticleManager();
                    Article editArticle = new Article();
                    List<Article> editArticles = null;
                    try
                    {
                        editArticles = editArticleManager.GetArticles(Convert.ToInt32(e.CommandArgument));
                        if (editArticles != null && editArticles.Count > 0)
                        {
                            editArticle.ArticleID = editArticles[0].ArticleID;
                            editArticle.ArticleName = editArticles[0].ArticleName;
                            editArticle.ArticleImageUrl = editArticles[0].ArticleImageUrl;
                            editArticle.ArticleTypeID = editArticles[0].ArticleTypeID;
                            editArticle.VehicleModelID = editArticles[0].VehicleModelID;
                            editArticle.UserID = editArticles[0].UserID;
                            editArticle.VehicleModelTypeID = editArticles[0].VehicleModelTypeID;
                            editArticle.VehicleModelTypeYearID = editArticles[0].VehicleModelTypeYearID;
                            editArticle.IsPublished = editArticles[0].IsPublished;
                            editArticle.LastUpdatedDate = editArticles[0].LastUpdatedDate;
                            editArticle.IsActive = false;
                            this.PageSession.Article = editArticle;
                            Response.Redirect("edit_article.aspx", true);

                        }

                    }
                    catch (Exception)
                    {
                        this.pageActionMessage.InnerText = "Failed to assign article.";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                    finally
                    {
                        editArticleManager = null;
                        editArticles = null;
                        editArticle = null;

                    }
                    break;
                case "EditSteps":
                    ArticleManager stepArticleManager = new ArticleManager();
                    Article stepArticle = new Article();
                    List<Article> stepArticles = null;
                    try
                    {
                        stepArticles = stepArticleManager.GetArticles(Convert.ToInt32(e.CommandArgument));
                        if (stepArticles != null && stepArticles.Count > 0)
                        {
                                stepArticle.ArticleID = stepArticles[0].ArticleID;
                                stepArticle.ArticleName = stepArticles[0].ArticleName;
                                stepArticle.ArticleImageUrl = stepArticles[0].ArticleImageUrl;
                                stepArticle.ArticleTypeID = stepArticles[0].ArticleTypeID;
                                stepArticle.VehicleModelID = stepArticles[0].VehicleModelID;
                                stepArticle.UserID = stepArticles[0].UserID;
                                stepArticle.VehicleModelTypeID = stepArticles[0].VehicleModelTypeID;
                                stepArticle.VehicleModelTypeYearID = stepArticles[0].VehicleModelTypeYearID;
                                stepArticle.IsPublished = stepArticles[0].IsPublished;
                                stepArticle.LastUpdatedDate = stepArticles[0].LastUpdatedDate;
                                stepArticle.IsActive = false;
                                this.PageSession.Article = stepArticle;
                                Response.Redirect("step_list.aspx", true);                           

                        }

                    }
                    catch (Exception)
                    {
                        this.pageActionMessage.InnerText = "Failed to assign article.";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                    finally
                    {
                        stepArticleManager = null;
                        stepArticles = null;
                        stepArticle = null;

                    }
                    break;
                default:
                    break;
            }

        }
        /// <summary>
        /// Handles the item databound event of the Datalist control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void dtlArticles_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            GetUserArticle userArticle = (GetUserArticle)e.Item.DataItem;
            Button editButton = (Button)e.Item.FindControl("btnEditArticle");
            LinkButton lnkEditSteps = (LinkButton)e.Item.FindControl("lnkEditSteps");
            LinkButton lnkEditArticle = (LinkButton)e.Item.FindControl("lnkEditArticle");
            if (userArticle.IsPublished)
            {
                editButton.Visible = false;
                lnkEditArticle.Enabled = false;
            }
            else
            {
                editButton.Visible = true;
                lnkEditArticle.Enabled = true;
            }


        }
        #endregion

        #region [Private Methods]
        /// <summary>
        /// Binds the datalist
        /// </summary>
        private void LoadPage()
        {
            ArticleManager articleManager = new ArticleManager();
            List<GetUserArticle> userArticles = null;
            try
            {

                userArticles = articleManager.GetUserArticle(this.PageSession.ApplicationUser.UserID);
                userArticles = (from ua in userArticles group ua by ua.ArticleID into g select g.First()).ToList();
                if (userArticles != null && userArticles.Count > 0)
                {
                    foreach (GetUserArticle userArticle in userArticles)
                    {
                        if (userArticle.ArticleImageUrl != string.Empty)
                        {
                            StringBuilder path = new StringBuilder();
                            path.Append(AppConfiguration.ArticlePath);
                            path.Append("/");
                            path.Append(userArticle.ArticleID);
                            path.Append("/");
                            path.Append(userArticle.ArticleImageUrl);
                            userArticle.ArticleImageUrl = path.ToString();
                            path = null;
                        }
                        else
                        {
                            userArticle.ArticleImageUrl = "images/imgNoArticleImage.jpg";

                        }
                        userArticle.IsPublished = userArticle.IsPublished;
                        userArticle.ArticleTypeName = GetArticleTypeName(userArticle.ArticleTypeID);
                        if (userArticle.ArticleTypeID == (int)ArticleEnums.Blog)
                        {
                            StringBuilder pathToFile = new StringBuilder();
                            pathToFile.Append(AppConfiguration.ArticlePath);
                            pathToFile.Append("/");
                            pathToFile.Append(userArticle.ArticleID);
                            pathToFile.Append("/");
                            pathToFile.Append(userArticle.StepURL);
                            string completePath = Server.MapPath(pathToFile.ToString());
                            if (LoadStepData(completePath).Count() > 100)
                            {
                                userArticle.StepContent = LoadStepData(completePath).Substring(0, 100) + "...";
                            }
                            else
                            {
                                userArticle.StepContent = LoadStepData(completePath);
                            }

                            pathToFile = null;
                        }


                    }
                    this.dtlArticles.DataSource = userArticles;
                    this.dtlArticles.DataBind();
                }
                else
                {
                    this.pageActionMessage.InnerText = "There are no articles. Try adding articles by going to create article page.";
                    this.pageActionMessage.Attributes.Add("class", "information-msg");
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to load the articles";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                articleManager = null;
                userArticles = null;
            }
        }

        /// <summary>
        /// Gets the article type name
        /// </summary>
        /// <param name="articleTypeID">articleTypeID</param>
        /// <returns>articleTypeName</returns>
        private string GetArticleTypeName(int articleTypeID)
        {
            string articleTypeName = string.Empty;
            switch (articleTypeID)
            {
                case (int)ArticleEnums.Blog:
                    articleTypeName = "Blog";

                    break;
                case (int)ArticleEnums.Video:
                    articleTypeName = "Video";
                    break;
                default:
                    break;
            }
            return articleTypeName;
        }

        /// <summary>
        /// Reads the loaded  data
        /// </summary>
        /// <param name="stepURL">the step url</param>
        /// <returns>the lines in the text</returns>
        private string LoadStepData(string stepURL)
        {
                
            string lines = System.IO.File.ReadAllText(stepURL);
            return lines;
            
        }
        #endregion



    }
}